#!/usr/bin/env node
const path = require('path');
const fs = require('fs');

const { selectTemplate, templateTransform, insertRoute } = require('./scripts');

const filesOutput = (template, componentName) => {
  // 读取配置
  let comp = componentName;
  if (!componentName) {
    comp = `MyComponent${Math.floor(Math.random() * 100)}`;
  }
  const { config } = require(path.join(global.cwdPath, './.yhpagerc.js'));
  const { basePath, storeType } = config;
  const hbs_path = path
    .join(global.appRoot, `hbs/${template}/index.hbs`)
    .replace(/\\/g, '/');
  const renderFunc =
    templateTransform[storeType === 'mobx' ? 'handleMobx' : 'handleRedux'];
  const evtsPath = path
    .join(global.appRoot, `hbs/${template}/evts.js`)
    .replace(/\\/g, '/');
  const isExsit = fs.existsSync(evtsPath);
  const evts = isExsit ? require(evtsPath) : [];
  const json = {
    evts,
    hbs_path,
    target: path.join(global.cwdPath, basePath, '/').replace(/\\/g, '/'),
    componentName: comp,
    template,
  };
  renderFunc(json);
  insertRoute(componentName);
};

function main() {
  const { config } = require(path.join(global.cwdPath, './.yhpagerc.js'));
  global.config = config;

  selectTemplate().then(({ template, componentName }) =>
    filesOutput(template, componentName)
  );
}

module.exports = {
  filesOutput,
  new_main: main,
};
